
var Token = require('../service/token');
var User = require('../service/user');

var notRequired = [
    '/api/sign/signin', // login page
    '/api/sign/signup' // regist page
];

/**
 * 登陆拦截中间件。
 **/
exports.userRequired = function(req, res, next) {
    var url = req.originalUrl;
    for (var i = 0, len = notRequired.length; i !== len; ++i) {
        if (url.indexOf(notRequired[i]) >= 0) {
            return next();
        }
    }

    var access_token = req.query.access_token;
    var authorization = req.get('Authorization');

    if (!!!access_token && !!authorization && authorization.indexOf('token') != -1) {
        var tokenBeginIndex = authorization.indexOf('token');
        access_token = authorization.substr(tokenBeginIndex + 6);
    }

    if (!access_token) {
        res.status(401).json({msg: '请先登录。'})
        return;
    }

    Token.findToken(access_token, function(err, token) {
        if (err) return next(err);
        if (!token) {
            res.status(401).json({msg: '请先登录。'})
            return;
        }

        // 可以放到专业缓存中，避免每次查询。
        User.getUserById(token.user_id, function(err, user){
            if(err) return next(err);
            req.user = user;
            next();
        })
    });
}
